import Taro ,{ Component } from '@tarojs/taro'
import { View , Image , Text , Canvas , Button} from '@tarojs/components'

import {
  AtTag , AtFloatLayout
} from 'taro-ui'

import './shopDetail.scss'

import DetailToolBar from '../../component/DetailToolBar/detailToolBar.js';

import DataManager from '../../utils/DataManager.js'
import {base_url} from "../../network/config";

import location_icon from '../../image/ic_location.png'

import BasePage from '../basePage.js'
import {STORAGE_KEY} from "../../utils/const";


export default class shopDetail extends BasePage{
  config = {
    navigationBarTitleText: '便民详情'
  }

  defaultProps = {
    shopName:'',
    shopId:''
  }

  constructor() {
    super(...arguments)
    this.state={
      shopDetailData:{},
      shareTempFilePath:'',
      shopHead:'',
      weixinCodeImage:'',
      screenWidth:Number,
      screenHeight:Number,
      shareShow:false,
    }
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  onShareAppMessage(options){
    console.log('---shop-----options=======' + JSON.stringify(options))
    let _this = this;
    if (options.from == 'button'){
      // 转发成功
      let url = base_url + 'rest/user/share/save';
      Taro.request({
        url:url,
        data: {
          token:DataManager.getToken(),
          platform:'android_c',
          weixinId:DataManager.getWeiXinId(),
          loginChannel:'c',
          appId:'KC876D98B30UA40CJSNHI689FB33SDW',
          digest : 'dda484557c12febe48139d8f44051c13',
          id:_this.shopId,
          type:3,
        },
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        method: 'POST',
        success(res) {
        }
      })
      return {
        path: `/pages/shop/shopDetail?shopId=` + _this.shopId + `&shareUserId=` + DataManager.getUserId()
      }
    }
  }

  componentWillMount (e) {

    let systemInfo = Taro.getSystemInfoSync();
    this.setState({
      screenWidth:systemInfo.windowWidth,
      screenHeight:systemInfo.windowHeight,
    })

    console.log('scene-----------' + Taro.getStorageSync(STORAGE_KEY.SCENE));
    this.shopId = this.$router.params.shopId;

    if (Taro.getStorageSync(STORAGE_KEY.SCENE)){
      this.shopId = Taro.getStorageSync(STORAGE_KEY.SCENE);
      Taro.setStorageSync(STORAGE_KEY.SCENE, ''); //  scene只使用一次  否则进入其他详情id会错乱
    }

    let shareUserId = this.$router.params.shareUserId;

    if (shareUserId && DataManager.getUserId() != shareUserId){ // 保证自己的userID 和分享人 的userId 不一致 否则会出现自己点自己分享的链接问题
      Taro.setStorageSync(STORAGE_KEY.SHARE_USER_ID , shareUserId);
    }
  }

  componentDidMount(){
    this.loadShopDetail()
  }

  createPoster(){

    let midX = (this.state.screenWidth - 80) / 2

    let that = this;
    const ctx = Taro.createCanvasContext('share')

    console.log('screen-----------' + this.state.screenWidth + '   ' + this.state.screenHeight)

    ctx.beginPath()
    ctx.setFillStyle('white')
    ctx.arc(10, 40 + 10, 10, Math.PI, Math.PI * 1.5)
    // border-top
    ctx.moveTo(10, 40)
    ctx.lineTo(this.state.screenWidth - 10, 40)
    ctx.lineTo(this.state.screenWidth, 40 + 10)
    // 右上角
    ctx.arc(this.state.screenWidth - 10, 40 + 10, 10, Math.PI * 1.5, Math.PI * 2)
    // border-right
    ctx.lineTo(this.state.screenWidth, 40 + 500 - 10)
    ctx.lineTo(this.state.screenWidth - 10, 40 + 500)
    // 右下角
    ctx.arc(this.state.screenWidth - 10, 40 + 500 - 10, 10, 0, Math.PI * 0.5)
    // border-bottom
    ctx.lineTo(10, 40 + 500)
    ctx.lineTo(0, 40 + 500 - 10)
    // 左下角
    ctx.arc(10, 40 + 500 - 10, 10, Math.PI * 0.5, Math.PI)
    // border-left
    ctx.lineTo(0, 40 + 10)
    ctx.lineTo(10, 40)
    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.fill()
    // ctx.stroke()
    ctx.closePath()
    // 剪切
    ctx.clip()
    ctx.restore();
    ctx.draw(true)

    ctx.drawImage(this.state.weixinCodeImage ,20,350,100,100)
    ctx.draw(true);

    ctx.setFontSize(12);
    ctx.setFillStyle('#333333');
    ctx.fillText('长按识别图中二维码',
      140, 380)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(12);
    ctx.setFillStyle('#333333');
    ctx.fillText('查看活动详情信息',
      140, 420)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(18);
    ctx.setFillStyle('#333333');
    ctx.fillText(this.state.shopDetailData.businessName,
      115, 85)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    ctx.setFontSize(14);
    ctx.setFillStyle('#436EEE')
    ctx.fillText(this.state.shopDetailData.categoryName,
      115, 130)
    ctx.fill();
    ctx.restore();
    ctx.draw(true);

    this.drawText(ctx,this.state.shopDetailData.content.replace('\n',' ') ,20 , 170, 148 , this.state.screenWidth - 60)

    ctx.arc(60, 100, 40, 0, Math.PI * 2)
    ctx.clip();
    ctx.drawImage(this.state.shopHead,20,60,80,80);
    ctx.restore();
    ctx.draw(true);

    setTimeout(function () {
      Taro.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 375,
        height: 667,
        canvasId: 'share',
        quality:1,
        success: function (res) {
          if (!res.tempFilePath) {
            Taro.showModal({
              title: '提示',
              content: '图片绘制中，请稍后重试',
              showCancel: false
            })
          } else {
            console.log('tempFile==================' + res.tempFilePath)
            that.setState({
              shareTempFilePath: res.tempFilePath,
              shareShow:true
            })
            //
            // let imageArray = [];
            // imageArray.push(res.tempFilePath);
            //
            // console.log('imagearray========' + imageArray[0])
            //
            // Taro.previewImage({
            //   urls:imageArray
            // })
          }
        }
      })
    } , 200)
  }

  drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    ctx.setFontSize(14);
    ctx.setFillStyle('#666666')

    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 18; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  }

  loadShopDetail(){
    let _this = this;

    let url = base_url + 'stateless/category/news/categoryNewsDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        newsId:_this.shopId
      },
      method: 'GET',
      success(res) {

        console.log('shopdetail-----' + JSON.stringify(res))

        _this.setState({
          shopDetailData:res.data.data,
        })

        Taro.downloadFile({
          url:res.data.data.imageUrl,
          success: function (res2) {
            console.log(res2);
            _this.setState({
              shopHead:res2.tempFilePath
            })
          }
        })
      }
    })
  }

  onCheckLocation = () =>{
    const latitude =  this.state.shopDetailData.latitude
    const longitude =  this.state.shopDetailData.longitude
    Taro.openLocation({
      latitude,
      longitude,
      scale: 18
    })
  }

  onSharePost = () =>{

    let pageData = 'pages/shop/shopDetail';

    let _this = this;
    let url = base_url + 'stateless/weixin/code/weixinCodeDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        businessId:_this.shopId,
        businessType:4,
        page:pageData
      },
      method: 'GET',
      success(res) {
        console.log('weixinCode-----' + JSON.stringify(res))
        if (res.data && res.data.data && res.data.data.weixinCode){
          Taro.showLoading({
            title : '图片生成中...'
          });
          Taro.downloadFile({
            url:res.data.data.weixinCode,
            success: function (res2) {
              console.log('this.state.weixinCodeImag =======' +res2.tempFilePath)
              _this.setState({
                weixinCodeImage:res2.tempFilePath
              })
              setTimeout(function () {
                Taro.hideLoading();
                _this.createPoster();
              } , 200)
            },
          })
        }
      }
    })
  }

  saveSharePic = () =>{
    Taro.saveImageToPhotosAlbum({
      filePath: this.state.shareTempFilePath,
      success(res) {
        console.log("保存图片成功")
        console.log(res)
        Taro.showToast({
          title: '保存成功',
          duration: 2000
        })
      },
      fail(err) {
        console.log('失败')
        console.log(err)

        if (err.errMsg == "saveImageToPhotosAlbum:fail cancel") {
          Taro.openSetting({
            success(settingdata) {
              console.log(settingdata)
              if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
              } else {
                console.log('获取权限失败，给出不给权限就无法正常使用的提示')
              }
            }
          })
        }
      }
    })
  }

  onShareClose = () =>{
    this.setState({shareShow:false})
  }

  render() {
    let shopData = this.state.shopDetailData;
    let shopImages = shopData ? shopData.newsImages : null;

    return(
      <View className='shop-detail-container'>
        <View style='width:0px;height:0px;overflow:hidden;'>
          <Canvas canvasId='share' style='width:750px;height:1334px;position:fixed;left:9000px;'></Canvas>
        </View>

        <View className='shop-detail-head-container'>
          <Image className='shop-detail-cover-image' src={shopData.headUrl} />
          <View className='shop-detail-container-sub'>
            <Text className='shop-detail-name'>{shopData.userName}</Text>
            <AtTag active size='small' style='margin-top: 5px'>
              {shopData.categoryName}
            </AtTag>
          </View>
          <Text className='shop-detail-publish-time'>{shopData.releaseStrDate}</Text>
        </View>
        <View className='shop-detail-address-container' onClick={this.onCheckLocation.bind(this)}>
          <Image style='width:20px;height:20px' src={location_icon} />
          <Text className='shop-detail-address'>{shopData.businessAddress}</Text>
        </View>
        <View className='shop-detail-divider'></View>
        <Text className='shop-detail-content'>{shopData.content}</Text>
        <View className='shop-detail-image-container'>
          {shopImages && shopImages.map(item => {
            return (<Image src={item.imageUrl} mode='widthFix' style='margin-top:10px;width:90%'></Image>)
          })}
        </View>
        <DetailToolBar itemId={shopData.id} mobileNumber={shopData.mobile}
                       itemType={5} hasCollect={shopData.isCollect}
        />
        <View className='shop-detail-share'  onClick={this.onSharePost.bind(this)}>
          <Text className='shop-detail-share-text'>分享</Text>
          <Text className='shop-detail-share-text'>海报</Text>
        </View>
        <AtFloatLayout
          isOpened={this.state.shareShow}
          scrollY
          onClose={this.onShareClose.bind(this)}
          title='分享到朋友圈'
        >
          <View className='detail-share-container'>
            <Image className='detail-share-img' src={this.state.shareTempFilePath}></Image>
            <Button className='detail-share-btn-post' onClick={this.saveSharePic.bind(this)}>保存图片</Button>
            <Text className='detail-share-hint'>保存图片到手机后，您可到朋友圈分享该图片</Text>
          </View>
        </AtFloatLayout>
      </View>
    )
  }
}
